package com.fingard.dsp.bank.directbank.ccb02.util;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import org.apache.commons.codec.binary.Base64;


/**
 * 功能：加解密类
 */
public class DESedeCoder {

    public static final String KEY_ALGORITHM = "DESede";

    /**
     * 算法/工作模式/填充方式
     */
    public static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";

    /**
     * 转换密码
     * @param key
     * @return
     * @throws Exception
     */
    private static Key toKey(byte[] key) throws Exception{

        DESedeKeySpec dks = new DESedeKeySpec(key);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);

        return keyFactory.generateSecret(dks);

    }

    /**
     * 加密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception{

        Key k = toKey(key);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        cipher.init(Cipher.ENCRYPT_MODE, k);

        return cipher.doFinal(data);
    }

    /**
     * 加密
     * @param data
     * @param sBase64Key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, String sBase64Key) throws Exception{

        byte[] key = Base64.decodeBase64(sBase64Key);

        Key k = toKey(key);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        cipher.init(Cipher.ENCRYPT_MODE, k);

        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception{

        Key k = toKey(key);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        cipher.init(Cipher.DECRYPT_MODE, k);

        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @param data
     * @param sBase64Key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, String sBase64Key) throws Exception{

        byte[] key = Base64.decodeBase64(sBase64Key);

        Key k = toKey(key);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        cipher.init(Cipher.DECRYPT_MODE, k);

        return cipher.doFinal(data);
    }

}

